package tbalert.web.view;


import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.springframework.web.servlet.view.document.AbstractJExcelView;

import tbalert.web.ExcelConstants;
import tbalert.web.MyBeanUtils;
import tbalert.web.entity.BaseInfo;

public class ViewJzkExcel extends AbstractJExcelView {

	private String downloadFileName;

	@SuppressWarnings("unchecked")
	@Override
	protected void buildExcelDocument(Map<String, Object> model, WritableWorkbook workbook,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取得列表信息
		List<BaseInfo> baseInfoList = (List<BaseInfo>) model.get("baseInfoList");

		// 设置文件响应信息
		String showFileName = URLEncoder.encode(downloadFileName + ".xls", "UTF-8");
		response.setContentType("application/msexcel");// 定义输出类型
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control", "max-age=30");
		response.setHeader("Content-disposition", "attachment; filename=" + showFileName);

		// 初始化参数
		WritableSheet sheet = workbook.createSheet("baseinfo-ymjg", 1);
		int i = 0, j = 0;
		String label = null;
		setTitle(sheet, i, j);
		for (BaseInfo baseInfo : baseInfoList) {
			i++;
			j = 0;
//			if (i % 50 == 0) {
//				setTitle(sheet, i, j);
//				continue;
//			}
			sheet.addCell(new Label(j, i, baseInfo.getDjdw().getDwmc()));
			j++;
			for (String field : ExcelConstants.baseInfoList) {
				sheet.addCell(new Label(j, i, MyBeanUtils.getFieldStrValue(baseInfo, field)));
				j++;
			}
			if(baseInfo.getYmjg()!=null && baseInfo.getYmjg().getTbdw()!=null){
				label = baseInfo.getYmjg().getTbdw().getDwmc();
				sheet.addCell(new Label(j, i, label));
			}
			j++;
			for (String field : ExcelConstants.ymjgList) {
				sheet.addCell(new Label(j, i, MyBeanUtils.getFieldStrValue(baseInfo.getYmjg(), field)));
				j++;
			}
		}
	}

	private void setTitle(WritableSheet sheet, int i, int j) throws Exception {
		sheet.addCell(new Label(j, i, "登记单位"));
		j++;
		for (String field : ExcelConstants.baseInfoList) {
			sheet.addCell(new Label(j, i, ExcelConstants.baseinfoTit.get(field)));
			j++;
		}
		sheet.addCell(new Label(j, i, "结果录入单位"));
		j++;
		for (String field : ExcelConstants.ymjgList) {
			sheet.addCell(new Label(j, i, ExcelConstants.ymjgTit.get(field)));
			j++;
		}
	}

	public String getDownloadFileName() {
		return downloadFileName;
	}

	public void setDownloadFileName(String downloadFileName) {
		this.downloadFileName = downloadFileName;
	}
}
